package com.dmyang.controller;

import com.dmyang.common.pojo.HyResult;
import com.dmyang.common.utils.CheckCodeUtil;
import com.dmyang.common.utils.CookieUtils;
import com.dmyang.entity.HyArticle;
import com.dmyang.entity.HyCategory;
import com.dmyang.entity.HyComment;
import com.dmyang.entity.HyMessage;
import com.dmyang.service.ArticleService;
import com.dmyang.service.CategoryService;
import com.dmyang.service.CommentService;
import com.dmyang.service.MessageService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Date;
import java.util.Enumeration;
import java.util.List;
import java.util.Map;

/**
 * 页面跳转Controller
 * Created by brss on 2017/8/8.
 */
@Controller
public class PageController {

    @Autowired
    private ArticleService articleService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private MessageService messageService;
    @Autowired
    private CommentService commentService;

    /**
     * 跳转到首页,并且查询，加载首页的内容
     *
     * @return
     */
    @RequestMapping("/index")
    public String index(HttpServletRequest request) {
        List<HyArticle> list = articleService.showLastestArticle(10);
        request.setAttribute("articles", list);
        List<HyCategory> categories = categoryService.showAllCategory();
        request.setAttribute("categories", categories);

        return "index";
    }

    /**
     * 跳转到文章详情页
     *
     * @param id 要获取文章的id值
     * @param page 传入要跳转到留言的第几页
     * @param request
     * @return
     */
    @RequestMapping("/portal/showOneArticle/{id}")
    public String showOneArticle(@PathVariable("id") Integer id,
                                 @RequestParam(defaultValue = "1") Integer page ,
                                 HttpServletRequest request) {
        try {
            //获取文章
            HyArticle article = articleService.findArticleById(id);
            request.setAttribute("item", article);
            //获取所有分类
            List<HyCategory> categories = categoryService.showAllCategory();
            request.setAttribute("categories", categories);
            //获取留言（分页）
            Map<?, ?> map = commentService.showComment(5, id, page);
            request.setAttribute("currentPage", map.get("currentPage"));
            request.setAttribute("totalPages", map.get("totalPages"));
            request.setAttribute("comments", map.get("comments"));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "articleContent";

    }

    /**
     * 根据分类id展示文章
     *
     * @param categoryId
     * @param request
     * @return
     */
    @RequestMapping("/portal/showArcleFrmCate/{categoryId}")
    public String showArticleByCate(@PathVariable("categoryId") Integer categoryId, HttpServletRequest request) {
        List<HyArticle> articles = articleService.showArticleByCate(categoryId);
        request.setAttribute("articles", articles);
        List<HyCategory> categories = categoryService.showAllCategory();
        request.setAttribute("categories", categories);
        request.setAttribute("categoryId", categoryId);
        return "index";
    }

    /**
     * 展示留言板页面
     *
     * @param request
     * @return
     */
    @RequestMapping("/portal/showMessage")
    public String showMessagePage(@RequestParam(defaultValue = "1") Integer page, HttpServletRequest request) {
        //每页要展示的页数
        Integer pageSize = 10;
        Map<?, ?> map = messageService.showMessageList(pageSize, page);
        request.setAttribute("messages", map.get("result"));
        request.setAttribute("currentPage", page);
        request.setAttribute("totalPages", map.get("totalPages"));
        return "message";
    }

    /**
     * 生成验证码
     *
     * @param request
     * @param response
     */
    @RequestMapping("/portal/code")
    public void genCheckCode(HttpServletRequest request, HttpServletResponse response) {
        try {
            CheckCodeUtil util = CheckCodeUtil.Instance();
            String jsessionid = CookieUtils.getCookieValue(request, "JSESSIONID");
            request.getSession().setAttribute(jsessionid, util.getStr());
            ServletOutputStream stream = response.getOutputStream();
            ImageIO.write(util.getImage(), "JPEG", stream);
            stream.flush();
            stream.close();

        } catch (Exception e) {
            System.out.println("生成验证码失败！");
        }
    }

    /**
     * 提交一条留言
     *
     * @param veriCode 验证码
     * @param messageContent 内容
     * @param nickname 昵称
     * @return
     */
    @RequestMapping("/portal/addMessage")
    @ResponseBody
    public HyResult addMessage(String veriCode, String messageContent,String nickname, HttpServletRequest request) {
        //判断验证码是否正确
        String jsessionid = CookieUtils.getCookieValue(request, "JSESSIONID");
        String code= (String) request.getSession().getAttribute(jsessionid);
        if (StringUtils.isBlank(code)){
            return HyResult.build(500,"错误：无法获取到你的信息，请刷新！");
        }
        if (!code.equals(veriCode)){
            return HyResult.build(500,"验证码不正确!");
        }
        //验证成功后，删除sesson
        request.getSession().removeAttribute(jsessionid);
        //调用Service，插入数据
        HyMessage message = new HyMessage();
        message.setCreateDate(new Date());
        message.setMessageContent(messageContent);
        message.setNickname(nickname);
        try {
            HyResult result = messageService.addMessage(message);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            return HyResult.build(500,"插入失败！");
        }
    }

    /**
     * 展示关于我页面
     * @return
     */
    @RequestMapping("/portal/showAbout")
    public String showAbout(){
        return "about";
    }

    /**
     * 添加一条评论
     * @param comment
     * @return
     */
    @RequestMapping("/portal/addComment")
    @ResponseBody
    public HyResult addComment(HyComment comment,String veriCode, HttpServletRequest request){
        //判断验证码是否正确
        String jsessionid = CookieUtils.getCookieValue(request, "JSESSIONID");
        String code= (String) request.getSession().getAttribute(jsessionid);
        if (StringUtils.isBlank(code)){
            return HyResult.build(500,"错误：无法获取到你的信息，请刷新！");
        }
        if (!code.equals(veriCode)){
            return HyResult.build(500,"验证码不正确!");
        }
        //验证成功后，删除sesson
        request.getSession().removeAttribute(jsessionid);
        //插入数据
        try {
            comment.setCreateTime(new Date());
            HyResult result = commentService.addComment(comment);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            return HyResult.build(500,"添加失败！");
        }
    }

}
